package com.supermarket.config.interceptor;

import com.supermarket.config.LoggingConfig.LoggingProperties;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * 请求日志拦截器
 * 记录所有请求信息并打印到控制台
 */
@Component
public class RequestLogInterceptor implements HandlerInterceptor {
    
    private static final Logger logger = LoggerFactory.getLogger(RequestLogInterceptor.class);
    
    @Autowired
    private LoggingProperties loggingProperties;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果日志记录被禁用，直接放行请求
        if (!loggingProperties.isEnabled()) {
            return true;
        }
        
        // 记录请求开始时间
        long startTime = System.currentTimeMillis();
        request.setAttribute("startTime", startTime);
        
        // 打印请求信息
        String method = request.getMethod();
        String uri = request.getRequestURI();
        String queryString = request.getQueryString();
        String remoteAddr = request.getRemoteAddr();
        
        // 打印请求基本信息
        System.out.println("\n==========请求开始==========");
        System.out.println("请求方法: " + method);
        System.out.println("请求URI: " + uri);
        if (loggingProperties.isIncludeQueryParams() && queryString != null) {
            System.out.println("请求参数: " + queryString);
        }
        System.out.println("客户端IP: " + remoteAddr);
        
        // 打印请求头信息
        if (loggingProperties.isIncludeHeaders()) {
            Map<String, String> headerMap = new HashMap<>();
            Enumeration<String> headerNames = request.getHeaderNames();
            if (headerNames != null) {
                while (headerNames.hasMoreElements()) {
                    String headerName = headerNames.nextElement();
                    headerMap.put(headerName, request.getHeader(headerName));
                }
                
                System.out.println("请求头信息: ");
                for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                    System.out.println("  " + entry.getKey() + ": " + entry.getValue());
                }
            }
        }
        
        // 打印请求参数信息
        if (loggingProperties.isIncludeQueryParams()) {
            Map<String, String[]> parameterMap = request.getParameterMap();
            if (!parameterMap.isEmpty()) {
                System.out.println("请求参数详情: ");
                for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
                    System.out.println("  " + entry.getKey() + ": " + String.join(", ", entry.getValue()));
                }
            }
        }
        
        return true;
    }
    
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 此方法在控制器处理请求后调用
    }
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 如果日志记录被禁用，直接返回
        if (!loggingProperties.isEnabled()) {
            return;
        }
        
        // 计算请求处理时间
        Long startTime = (Long) request.getAttribute("startTime");
        if (startTime != null) {
            long endTime = System.currentTimeMillis();
            long executionTime = endTime - startTime;
            
            // 打印响应信息
            int status = response.getStatus();
            
            System.out.println("响应状态码: " + status);
            System.out.println("处理时间: " + executionTime + "ms");
            System.out.println("==========请求结束==========\n");
        }
    }
} 